layui.config({
    base: CXL.ctxPath + '/externaljs/'
}).extend({ //设定组件别名
    echarts: 'echarts/echarts',
    axios: 'axios/axios',
    konva: 'konva/konva'
});
layui.use(['echarts', 'element', 'layer', 'carousel','konva'], function () {
    var element = layui.element;
    var $ = layui.$;
    var carousel = layui.carousel;
    var echarts = layui.echarts;

    //定义图表对象
    var myChart1 = null;
    var myChart2 = null;
    var myChart3 = null;
    var myChart4 = null;
    var myChart5 = null;
    var myChart6 = null;
    var myChart7 = null;

    var echartsList = [myChart1, myChart2, myChart3, myChart4];
    var firstOutputchart = document.getElementById('firstCraneOutputBar');
    var secondOutputchart = document.getElementById('secondCraneOutputBar');
    var thirdOutputchart = document.getElementById('thirdCraneOutputBar');
    var fourthOutputchart = document.getElementById('fourthCraneOutputBar');
    var chartList = [firstOutputchart, secondOutputchart, thirdOutputchart, fourthOutputchart];

    var width = $("#tabitem2").width() * 0.45;
    initPage();


    function initPage() {
        updateCraneOutput(1);
        updateCraneOutput(2);
        updateCraneOutput(3);
        updateCraneOutput(4);
        getTodayOutputNumber();
        getTodayFaultNumber();
        getFaultAndCount();

        setInterval(function (){
            $("#currentTime").html(getDate());
        },1000);
        setInterval(function (){
            intervalUpdateCraneOutput(1);
            intervalUpdateCraneOutput(2);
            intervalUpdateCraneOutput(3);
            intervalUpdateCraneOutput(4);
            IntervalGetFaultAndCount();
            getTodayOutputNumber();
            getTodayFaultNumber();
        },60000);

    }

//获取当前格式化时间
    function getDate(){
        var date = new Date();
        var year = date.getFullYear();    //  返回的是年份
        var month = date.getMonth() + 1;  //  返回的月份上个月的月份，记得+1才是当月
        var dates = date.getDate();
        var hour = date.getHours();          //  周一返回的是1，周六是6，但是周日是0
        var minute = date.getMinutes();
        if(minute<10){
            minute = "0"+minute;
        }//  周一返回的是1，周六是6，但是周日是0
        var second = date.getSeconds();
        if(second<10){
            second = "0"+ second.toString();
        }//  周一返回的是1，周六是6，但是周日是0
        var hour = date.getHours();          //  周一返回的是1，周六是6，但是周日是0
        var arr = [ "星期日","星期一","星期二","星期三","星期四","星期五","星期六"];
        return year+"年"+month+"月"+dates+"日"+" "+hour+":"+minute+":"+second;
    }
    /* $(".digits").numScroll({
            time:5000
     });*/

    // clocknum(12588,'requiredPeoples');


    //获取当天产量
    function getTodayOutputNumber(){
        $.ajax({
            url: CXL.ctxPath + "/semiautomatic/apartrecord/getApartNumberTodayNoParam",
            type: "GET",
            dataType: "json",
            success: function (res) {
                if (res.success) {
                    let todayOutputNumber = res.obj;
                    console.log(todayOutputNumber);
                    clocknum(parseInt(todayOutputNumber), 'todayOutputNumber'); //执行
                } else {
                    CXL.error(res.msg);
                }
            },
            fail: function () {
                CXL.error("网络错误！");
            }
        });
    }

    //获取当天错误数
    function getTodayFaultNumber(){
        $.ajax({
            url: CXL.ctxPath + "/common/faultrecord/getFaultNumberTodayNoParam",
            type: "GET",
            dataType: "json",
            success: function (res) {
                if (res.success) {
                    let todayFaultNumber = res.obj;
                    console.log(todayFaultNumber);
                    clocknum(parseInt(todayFaultNumber), 'todayFaultnumber'); //执行
                } else {
                    CXL.error(res.msg);
                }
            },
            fail: function () {
                CXL.error("网络错误！");
            }
        });
    }
    //定时更新图标
    function intervalUpdateCraneOutput(craneId){

        let xAxisData = [];
        let yAxisData = [];

        $.ajax({
            url: CXL.ctxPath + "/bigscreen/mainscreen/getTodayCraneOutput",
            data: {
                craneId: craneId
            },
            type: "POST",
            dataType: "json",
            success: function (res) {
                if (res.success) {
                    let craneOutputData = res.obj;
                    // console.log(craneOutputData);
                    for (let item of craneOutputData) {
                        xAxisData.push(item["name"]);
                        yAxisData.push(item["apart_count"]);
                    }
                    let thisMychart = echartsList[craneId - 1];// 基于准备好的dom，初始化echarts实例

                    let thisOption = getOutputChartOption(craneId,xAxisData,yAxisData);
                    thisMychart.setOption(thisOption,{notMerge:true});
                } else {
                    CXL.error(res.msg);
                }
            },
            fail: function () {
                CXL.error("网络错误！");
            }
        });
    }
    /**
     *    就业行业柱形图
     */
    function updateCraneOutput(craneId) {

        let xAxisData = [];
        let yAxisData = [];

        $.ajax({
            url: CXL.ctxPath + "/bigscreen/mainscreen/getTodayCraneOutput",
            data: {
                craneId: craneId
            },
            type: "POST",
            dataType: "json",
            success: function (res) {
                if (res.success) {
                    let craneOutputData = res.obj;
                    // console.log(craneOutputData);
                    for (let item of craneOutputData) {
                        xAxisData.push(item["name"]);
                        yAxisData.push(item["apart_count"]);
                    }
                    initCraneOutputBar(craneId, chartList[craneId - 1], xAxisData, yAxisData)
                } else {
                    CXL.error(res.msg);
                }
            },
            fail: function () {
                CXL.error("网络错误！");
            }
        });

    }


    function initCraneOutputBar(craneId, chart, xAxisData, yAxisData) {
        echartsList[craneId - 1] = echarts.init(chart);
        let thisMychart = echartsList[craneId - 1];// 基于准备好的dom，初始化echarts实例

        let thisOption = getOutputChartOption(craneId,xAxisData,yAxisData);
        thisMychart.setOption(thisOption, true);	    // 使用刚指定的配置项和数据显示图表。
        var app = {
            currentIndex: -1,
        };
        setInterval(function () {
            var dataLen = thisOption.series[0].data.length;

            // 取消之前高亮的图形
            echartsList[craneId - 1].dispatchAction({
                type: 'downplay',
                seriesIndex: 0,
                dataIndex: app.currentIndex
            });
            app.currentIndex = (app.currentIndex + 1) % dataLen;
            //console.log(app.currentIndex);
            // 高亮当前图形
            echartsList[craneId - 1].dispatchAction({
                type: 'highlight',
                seriesIndex: 0,
                dataIndex: app.currentIndex,
            });
            // 显示 tooltip
            echartsList[craneId - 1].dispatchAction({
                type: 'showTip',
                seriesIndex: 0,
                dataIndex: app.currentIndex
            });
        }, 1000);

        window.addEventListener('resize', function () {
            thisMychart.resize();
        });

        // height= $(window).height();//浏览器的高度
        // myChart.getDom().style.height = this.height+ "px";
        // myChart.resize();

        // $(document).ready(function () {
        //     myChart1.resize();
        // })
        // window.addEventListener("resize", function () {
        //     myChart1.resize();
        // });
    }


    //获取产量图配置
    function getOutputChartOption(craneId,xAxisData,yAxisData){
        let optionBase = {
            title: {
                text: craneId + '#天车产量',
                left: 'center',
                textStyle: {color: '#fff'},
                top: '4%',
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                    type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                }
            },
            grid: {
                left: '2%',
                right: '4%',
                top: '20%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: [
                {
                    type: 'category',
                    data: xAxisData,
                    axisTick: {
                        alignWithLabel: true
                    },
                    axisLabel: {		//x轴文字颜色
                        color: '#fff'
                    },
                    axisLine: {		    //x轴线的颜色
                        lineStyle: {
                            color: ['#fff'],
                            width: 1,
                            type: 'solid',
                            opacity: 0.1
                        }
                    }
                }
            ],
            yAxis: [
                {
                    type: 'value',
                    axisLabel: {		//y轴文字颜色
                        color: '#fff'
                    },
                    axisLine: {		    //y轴线的颜色
                        lineStyle: {
                            color: ['#fff'],
                            width: 1,
                            type: 'solid',
                            opacity: 0.1
                        }
                    },
                    splitLine: {        //网格样式
                        show: true,
                        lineStyle: {
                            color: 'rgba(255,255,255,0.1)',
                            width: 1,
                            type: 'dashed'
                        }
                    }
                }
            ],
            series: [
                {
                    name: '直接访问',
                    type: 'bar',
                    barWidth: '50%',
                    itemStyle: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                            offset: 0,
                            color: '#248ff7'
                        }, {
                            offset: 1,
                            color: '#6851f1'
                        }]),
                        borderRadius: 11,

                    },
                    data: yAxisData
                }
            ]
        };
        return optionBase;
    }
    function clocknum(num, id) {
        $('#' + id).empty();
        var html = '';
        var strarr = num.toString().split('');
        var digit_to_name = 'zero one two three four five six seven eight nine'.split(' ');
        for (var i = 0; i < strarr.length; i++) {
            if (strarr[i] == '.') {
                html += '<div class="dot"></div>'
            } else {
                var clasname = digit_to_name[strarr[i]];
                html += '<div class="' + clasname + '">' +
                    '<span class="d1"></span>' +
                    '<span class="d2"></span>' +
                    '<span class="d3"></span>' +
                    '<span class="d4"></span>' +
                    '<span class="d5"></span>' +
                    '<span class="d6"></span>' +
                    '<span class="d7"></span>' +
                    '</div>';
            }
        }
        $('#' + id).append(html);
    }

    //获取故障数目Data
    function getFaultAndCount(){
        $.ajax({
            url: CXL.ctxPath + "/common/faultrecord/getFaulttypeAndCount",
            type: "GET",
            dataType: "json",
            success: function (res) {
                if (res.success) {
                    let faultData = res.obj;
                    initFaultCountChart(faultData);
                } else {
                    CXL.error(res.msg);
                }
            },
            fail: function () {
                CXL.error("网络错误！");
            }
        });
    }

    //定时更新数据

    //获取故障数目Data
    function IntervalGetFaultAndCount(){
        $.ajax({
            url: CXL.ctxPath + "/common/faultrecord/getFaulttypeAndCount",
            type: "GET",
            dataType: "json",
            success: function (res) {
                if (res.success) {
                    let faultData = res.obj;
                    myChart6.setOption(getFaultBaseData(faultData),{notMerge:true});
                } else {
                    CXL.error(res.msg);
                }
            },
            fail: function () {
                CXL.error("网络错误！");
            }
        });
    }
    /**
     *    初始化故障记录图
     */
    function initFaultCountChart(data) {
        // console.log(data);

        myChart6 = echarts.init(document.getElementById('roseChart'));
        myChart6.setOption(getFaultBaseData(data),{notMerge:true});
        $(document).ready(function () {
            myChart6.resize();
        })
        window.addEventListener("resize", function () {
            myChart6.resize();
        });
    }

    //获取故障数的图基础数据
    function getFaultBaseData(data)
    {
       let faultOption = {
            color: ['#1d9dff', '#006cff', '#60cda0', '#ed8884', '#8b78f6', '#3a91d2', '#06a0ab', '#86c9f4'],
            title: {
                text: '故障类型统计',
                left: 'center',
                top: '4%',
                textStyle: {
                    color: '#fff'
                }
            },
            tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b} : {c} ({d}%)'
            },
            legend: {
                left: 'center',
                top: 'bottom',
                data: ['小车变频故障', '大车变频故障', '小车热继故障', '大车热继故障', '起升变频故障', '抓斗钢丝绳脱槽故障','主起升重锤故障', '其它'],
                textStyle: {
                    color: '#fff'
                }
            },
            toolbox: {
                show: true,
                feature: {
                    mark: {show: true},
                    dataView: {show: true, readOnly: false},
                    magicType: {
                        show: true,
                        type: ['pie', 'funnel']
                    },
                    restore: {show: true},
                    saveAsImage: {show: true}
                }
            },
            series: [
                {
                    name: '半径模式',
                    type: 'pie',
                    radius: [15, 90],
                    center: ['50%', '50%'],
                    roseType: 'radius',
                    label: {
                        show: true,
                        color: '#ff0'
                    },
                    emphasis: {
                        label: {
                            show: true,

                        }
                    },
                    data: data
                }
            ]
        };
       return faultOption;
    }

});

